package cn.akwing.sms.service.Impl;

import cn.akwing.sms.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class FileServiceImpl implements FileService {
    private String filepath="src/main/webapp/static/awards/";
    private String resPath = "/static/awards/";

    @Override
    public String upLoadFile(MultipartFile upload, Map<String, Object> map, String id) {
        String filetype = upload.getContentType();
        System.out.println("文件类型：" + filetype);
        assert filetype != null;
        if(!filetype.contains("image")){
            map.put("mes","文件类型错误，无法上传！");
            System.out.println("文件类型错误！");
        }else {
            String fileTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            String orgFileName = upload.getOriginalFilename();
            assert orgFileName != null;
            orgFileName = orgFileName.substring(orgFileName.lastIndexOf("."));
            String finalName = filepath + id + fileTime + orgFileName;
            System.out.println("完整文件名：" + finalName);
            File file = new File(filepath);
            if(!file.exists()){
                file.mkdir();
            }
            try {
                upload.transferTo(new File(finalName));
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                filepath="src/main/webapp/static/awards/";
            }
            return resPath+ id + fileTime + orgFileName;
        }
        return "error";
    }
}
